﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using DECOR.BL.BC;
using DECOR.BL.BE;
using System.Collections.Generic;

namespace DECOR.WebApp
{
    public partial class PlanFacturacion : System.Web.UI.Page
    {
        private void validaLogin()
        {
            if (Session["UsuarioWeb"] == null || Session["UsuarioSAP"] == null)
            {
                Response.Redirect("Login.aspx");
                //en vez de redireccionar, debería cerrar la pantalla
            }
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            this.validaLogin();
        }

        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                gvPlanFact.Enabled = true;
                ibtnAdd.Enabled = true;
                ibtnSet.Enabled = true;

                sesionCombos();
                cargar();

                addItem();
                string op = (string)Session["Operacion"];

                if (op.Equals("ver"))
                    bloquearPF(false);
                else
                    bloquearPF(true);
            }
            
        }

        private void bloquearPF(bool op){
            gvPlanFact.Enabled = op;
            ibtnAdd.Enabled = op;
            ibtnSet.Enabled = op;
        }
        private void cargar() {
            try
            {
                string numeroPedido = "";
                List<PlanFactBE> planFact = null;
                List<CatFactBE> CatFactBE;
                lblValorNeto.Text = (string) Session["Total"];

                if (Request.QueryString["np"] != null)
                {
                    numeroPedido = Request.QueryString["np"].ToString().PadLeft(10,'0');
                }
                if (Int64.Parse(numeroPedido) > 0)
                {
                    CatFactBE = new List<CatFactBE>();

                    planFact = PedidoBC.Instance.getPlanFact(numeroPedido, out CatFactBE);

                }
                else {
                    planFact = (List<PlanFactBE>)Session["planFact"];
                    if (planFact == null)
                    {
                        planFact = new List<PlanFactBE>();

                    }
                }
                
                Session["planFact"] = planFact;

                gvPlanFact.DataSource = planFact;
                gvPlanFact.DataBind();


            }
            catch (Exception ex)
            {
                Session["Mensaje"] = ex.Message;
            }
        
        }
        private void addItem() {

            List<PlanFactBE> planFact = null;
            planFact = (List<PlanFactBE>)Session["planFact"];
            decimal porcentaje = 0;
            bool add = true;
            foreach (PlanFactBE pf in planFact)
            {
                porcentaje += decimal.Round(pf.FPROZ / 100, 3);
                add = planFact[planFact.Count - 1].FKDAT.Year.Equals(1) ? false : true;
            }
            if (porcentaje < 1 && add){
            if (planFact == null) planFact = new List<PlanFactBE>();
            
            
            //{
                //if (!existe)
                //{
                    PlanFactBE planFactBE = new PlanFactBE();
                    
                    if (planFact.Count == 0)
                    {
                        planFactBE.FPROZ = 0;
                        planFactBE.FAKWR = planFactBE.FPROZ * decimal.Parse((string)Session["Total"]);
                    }
                    else {

                        planFactBE.FPROZ = (1 - porcentaje) * 100;
                        planFactBE.FAKWR = (1 - porcentaje) * decimal.Parse((string)Session["Total"]);
                    
                    }
                    planFactBE.TAXK1 = "I";

                    if (planFact.Count > 0)
                        planFactBE.FPLTR = (int.Parse(planFact[planFact.Count - 1].FPLTR) + 1).ToString().PadLeft(6, '0');
                    else
                        planFactBE.FPLTR = "000001";

                    planFact.Add(planFactBE);
                    Session["planFact"] = planFact;

                    gvPlanFact.DataSource = planFact;
                    gvPlanFact.DataBind();
              }
           
        }
        private void sesionCombos() { 

            List<GenericBE> lstDenom = new List<GenericBE>();
            List<GenericBE> lstMoneda = new List<GenericBE>();
            List<GenericBE> lstMotivoBloq = new List<GenericBE>();
            List<GenericBE> lstClaseDoc = new List<GenericBE>();
            List<GenericBE> lstRFACT = new List<GenericBE>();
            List<GenericBE> lstSTATU = new List<GenericBE>();
            List<GenericBE> lstTFPLU = new List<GenericBE>();
            List<GenericBE> lstCPag = new List<GenericBE>();
            
            ParametroBC.Instance.get_Param_PFact(ref  lstDenom, ref  lstMoneda,
                                                        ref lstMotivoBloq, ref lstClaseDoc, ref lstRFACT,
                                                        ref  lstSTATU, ref lstTFPLU,ref lstCPag);

            
            Session["lstDenom"] = lstDenom;
            Session["lstMoneda"] = lstMoneda;
            Session["lstMotivoBloq"] = lstMotivoBloq;
            Session["lstClaseDoc"] = lstClaseDoc;
            Session["lstRFACT"] = lstRFACT;
            Session["lstSTATU"] = lstSTATU;
            Session["lstTFPLU"] = lstTFPLU;
            Session["lstCPag"] = lstCPag;

            //cmbBloq.DataSource =lstMotivoBloq;
            //cmbBloq.DataTextField = "Descripcion";
            //cmbBloq.DataValueField = "Codigo";
            //cmbBloq.DataBind();

            //cmbCatF.DataSource = lstTFPLU;
            //cmbCatF.DataTextField = "Descripcion";
            //cmbCatF.DataValueField = "Codigo";
            //cmbCatF.DataBind();

            //cmbClaseFact.DataSource = lstClaseDoc;
            //cmbClaseFact.DataTextField = "Descripcion";
            //cmbClaseFact.DataValueField = "Codigo";
            //cmbClaseFact.DataBind();

            //cmbCpag.DataSource = lstCPag;
            //cmbCpag.DataTextField = "Descripcion";
            //cmbCpag.DataValueField = "Codigo";
            //cmbCpag.DataBind();

            //cmbDenom.DataSource = lstDenom;
            //cmbDenom.DataTextField = "Descripcion";
            //cmbDenom.DataValueField = "Codigo";
            //cmbDenom.DataBind();

            //cmbMoneda.DataSource = lstMoneda;
            //cmbMoneda.DataTextField = "Descripcion";
            //cmbMoneda.DataValueField = "Codigo";
            //cmbMoneda.DataBind();

            //cmbRglF.DataSource = lstRFACT;
            //cmbRglF.DataTextField = "Descripcion";
            //cmbRglF.DataValueField = "Codigo";
            //cmbRglF.DataBind();

            //cmbStatus.DataSource = lstSTATU;
            //cmbStatus.DataTextField = "Descripcion";
            //cmbStatus.DataValueField = "Codigo";
            //cmbStatus.DataBind();        
        }

        protected void gvPlanFact_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                List<GenericBE> lstDenom = (List<GenericBE>)Session["lstDenom"];
                List<GenericBE> lstMoneda = (List<GenericBE>)Session["lstMoneda"];
                List<GenericBE> lstMotivoBloq = (List<GenericBE>)Session["lstMotivoBloq"];
                List<GenericBE> lstClaseDoc = (List<GenericBE>)Session["lstClaseDoc"];
                List<GenericBE> lstRFACT = (List<GenericBE>)Session["lstRFACT"];
                List<GenericBE> lstSTATU = (List<GenericBE>)Session["lstSTATU"];
                List<GenericBE> lstTFPLU = (List<GenericBE>)Session["lstTFPLU"];
                List<GenericBE> lstCPag = (List<GenericBE>)Session["lstCPag"];

                List<PlanFactBE> planFact = (List<PlanFactBE>) Session["planFact"];

                 if (e.Row.RowType == DataControlRowType.DataRow)
                 {

                     HiddenField hidPosicion = (HiddenField)e.Row.FindControl("hidPosicion");
                     string posActual = hidPosicion.Value.PadLeft(6, '0');
                     PlanFactBE objItem = planFact.Find(delegate(PlanFactBE obj) { return obj.FPLTR == posActual; });

                    
                     //-----------------------------------------
                     if (((TextBox)e.Row.FindControl("txtFechaFact")).Text.Equals("01/01/0001 12:00:00 a.m."))
                        ((TextBox)e.Row.FindControl("txtFechaFact")).Text = string.Empty;

                     //---  Denominación de fecha
                     DropDownList cmbDenom = (DropDownList)e.Row.FindControl("cmbDenom");
                     if (cmbDenom != null)
                     {

                         cmbDenom.DataSource = lstDenom;
                         cmbDenom.DataTextField = "Descripcion";
                         cmbDenom.DataValueField = "Codigo";
                         cmbDenom.DataBind();
                         cmbDenom.SelectedValue = "";
                         if (objItem.TETXT != null)
                         {
                             cmbDenom.SelectedValue = objItem.TETXT;
                         }
                     }

                     //---  Moneda
                     DropDownList cmbBloq = (DropDownList)e.Row.FindControl("cmbBloq");
                     if (cmbBloq != null)
                     {
                         cmbBloq.DataSource = lstMotivoBloq;
                         cmbBloq.DataTextField = "Descripcion";
                         cmbBloq.DataValueField = "Codigo";
                         cmbBloq.DataBind();
                         //************************************************************************************
                         //se comentó a pedido del cliente mvelapatino, srenteria 27.06.2012 @@@ rhuapaya
                         //if (!((string)Session["Operacion"]).Equals("editar") && !((string)Session["Operacion"]).Equals("ver"))
                         //{
                         //    cmbBloq.SelectedValue = "02";
                         //}                            
                         //if (objItem.FAKSP != null)
                         //{
                         //    cmbBloq.SelectedValue = objItem.FAKSP;
                         //}
                         //************************************************************************************
                         //a pedido del cliente mvelapatina, srenteria 27.06.2012 @@@ rhuapaya
                         //se coloca por defecto el código 02
                         cmbBloq.SelectedValue = "02";
                         cmbBloq.Enabled = false;
                     }

                     //---  cmbRglF
                     DropDownList cmbRglF = (DropDownList)e.Row.FindControl("cmbRglF");
                     if (cmbRglF != null)
                     {

                         cmbRglF.DataSource = lstRFACT;
                         cmbRglF.DataTextField = "Descripcion";
                         cmbRglF.DataValueField = "Codigo";
                         cmbRglF.DataBind();
                         cmbRglF.SelectedValue = "1";
                         if (objItem.FAREG != null)
                         {
                             cmbRglF.SelectedValue = objItem.FAREG;
                         }
                     }

                     //---  status
                     DropDownList cmbStatus = (DropDownList)e.Row.FindControl("cmbStatus");
                     if (cmbStatus != null)
                     {

                         cmbStatus.DataSource = lstSTATU;
                         cmbStatus.DataTextField = "Descripcion";
                         cmbStatus.DataValueField = "Codigo";
                         cmbStatus.DataBind();
                         cmbStatus.SelectedValue = "A";
                         if (objItem.FKSAF != null)
                         {
                             cmbStatus.SelectedValue = objItem.FKSAF;
                         }
                     }

                     //---  condiciones de pago
                     DropDownList cmbCpag = (DropDownList)e.Row.FindControl("cmbCpag");
                     if (cmbCpag != null)
                     {

                         cmbCpag.DataSource = lstCPag;
                         cmbCpag.DataTextField = "Descripcion";
                         cmbCpag.DataValueField = "Codigo";
                         cmbCpag.DataBind();
                         cmbCpag.SelectedValue = "";
                         if (objItem.ZTERM != null)
                         {
                             cmbCpag.SelectedValue = objItem.ZTERM;
                         }
                     }
                     
                     //---  Categoria de Factura
                     DropDownList cmbCatF = (DropDownList)e.Row.FindControl("cmbCatF");
                     if (cmbCatF != null)
                     {

                         cmbCatF.DataSource = lstTFPLU;
                         cmbCatF.DataTextField = "Descripcion";
                         cmbCatF.DataValueField = "Codigo";
                         cmbCatF.DataBind();
                         cmbCatF.SelectedValue = "";
                         if (objItem.FPTTP != null)
                         {
                             cmbCatF.SelectedValue = objItem.FPTTP;
                         }
                     }
                     
                     //---  Clase de factura
                     DropDownList cmbClaseFact = (DropDownList)e.Row.FindControl("cmbClaseFact");
                     if (cmbClaseFact != null)
                     {

                         cmbClaseFact.DataSource = lstClaseDoc;
                         cmbClaseFact.DataTextField = "Descripcion";
                         cmbClaseFact.DataValueField = "Codigo";
                         cmbClaseFact.DataBind();
                         cmbClaseFact.SelectedValue = "ZFAC";
                         if (objItem.FKARV != null)
                         {
                             cmbClaseFact.SelectedValue = objItem.FKARV;
                         }
                     }
                     
                     //---  Clase de factura
                     DropDownList cmbMoneda = (DropDownList)e.Row.FindControl("cmbMoneda");
                     if (cmbMoneda != null)
                     {

                         cmbMoneda.DataSource = lstMoneda;
                         cmbMoneda.DataTextField = "Codigo";
                         cmbMoneda.DataValueField = "Codigo";
                         cmbMoneda.DataBind();
                         cmbMoneda.SelectedValue = "PEN";
                         if (objItem.WAERS != null)
                         {
                             cmbMoneda.SelectedValue = objItem.WAERS;//
                         }
                     }

                     //if ((objItem.TETXT.Equals("Z001") || objItem.TETXT.Equals("Z002")) && !objItem.FKSAF.Equals("") && !objItem.FAKSP.Equals("") && !objItem.TAXK1.Equals("I")) //bloqueo si la pos ya tiene factura asociada
                     //{
                     //    e.Row.Enabled = false;
                     //}
                 }
            }
            catch { 
            
            }
        }

        protected void ibtnSet_Click(object sender, ImageClickEventArgs e)
        {
            try
            {
                List<PlanFactBE> planFact = (List<PlanFactBE>)Session["planFact"];
                string numeroPedido = Request.QueryString["np"].ToString();

                
                foreach (GridViewRow dli in gvPlanFact.Rows)
                {
                    //eliminar items
                    if (!((TextBox)dli.FindControl("txtFechaFact")).Text.ToString().Equals(""))
                    {
                        CheckBox chkBorrar = (CheckBox)dli.FindControl("chkBorrar");
                        HiddenField hidPosicion = (HiddenField)dli.FindControl("hidPosicion");
                        if (hidPosicion != null)
                        {
                            PlanFactBE obj = planFact.Find(X => X.FPLTR == hidPosicion.Value);

                            if (chkBorrar != null && chkBorrar.Checked)
                            {

                                if (obj != null)
                                {
                                    obj.TAXK1 = "D";

                                }
                            }
                            //actualizo los datos de la lista

                            obj.FKDAT = DateTime.Parse(((TextBox)dli.FindControl("txtFechaFact")).Text.ToString());
                            obj.AFDAT = DateTime.Parse(((TextBox)dli.FindControl("txtFechaFact")).Text.ToString());
                            obj.TETXT = ((DropDownList)dli.FindControl("cmbDenom")).SelectedValue;

                            obj.FPROZ = decimal.Parse((((TextBox)dli.FindControl("txtPorc")).Text.ToString()));
                            obj.FAKWR = (obj.FPROZ / 100) * decimal.Parse((string)Session["Total"]);
                            obj.WAERS = ((DropDownList)dli.FindControl("cmbMoneda")).SelectedValue;

                            obj.FAKSP = ((DropDownList)dli.FindControl("cmbBloq")).SelectedValue;
                            obj.FAREG = ((DropDownList)dli.FindControl("cmbRglF")).SelectedValue;

                            obj.FKSAF = ((DropDownList)dli.FindControl("cmbStatus")).SelectedValue;

                            obj.ZTERM = ((DropDownList)dli.FindControl("cmbCpag")).SelectedValue;
                            obj.FPTTP = ((DropDownList)dli.FindControl("cmbCatF")).SelectedValue;
                            obj.FKARV = ((DropDownList)dli.FindControl("cmbClaseFact")).SelectedValue;



                        }
                    }
                    //--- fin eliminación
                }

                //------------------------------------------------------------------
                if (Int64.Parse( numeroPedido.PadLeft(10,'0'))>0)
                {

                    planFact.RemoveAll(x => x.AFDAT == null || x.AFDAT.Year.Equals(1));
                    PedidoBC.Instance.setPlanFact(numeroPedido, planFact,false);

                }
                else
                {
                    planFact.RemoveAll(X => X.TAXK1 == "D");
                }
                
                if (planFact.Count==0)
                    addItem();

                Session["planFact"] = planFact;
                cargar();
            }
            catch { }
        }
        protected void ibtnAdd_Click(object sender, ImageClickEventArgs e)
        {
            //List<PlanFactBE> planFact = null;
            //planFact = (List<PlanFactBE>)Session["planFact"];


            //if (planFact.Count < 2)
            //{
                addItem();

            //}
            //else
            //{   
            //    Session["Mensaje"] = "Se alcanzó el máximo de posiciones para el Plan de Facturción";
            //    ((Site)Master).muestraMensajes();
            //}
        }

    }
}
